package com.manman.eduService.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.manman.eduService.entity.EduSubject;
import com.manman.eduService.entity.excel.SubjectData;
import com.manman.eduService.entity.subject.OneSubject;
import com.manman.eduService.entity.subject.TwoSubject;
import com.manman.eduService.mapper.EduSubjectMapper;
import com.manman.eduService.service.EduSubjectService;
import com.manman.listener.SubjectExcelListener;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-01-29
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    // 添加课程分类
    @Override
    public void saveSubject(MultipartFile file, EduSubjectService subjectService) {
        try {
            // 文件输入流
            InputStream in = file.getInputStream();
            // 调用方法进行读取
            EasyExcel.read(in, SubjectData.class, new SubjectExcelListener(subjectService)).sheet().doRead();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<OneSubject> getAllSubject() {
        // 1. 查询出所有一级分类
        QueryWrapper<EduSubject> wrapperOne = new QueryWrapper<>();
        wrapperOne.eq("parent_id", "0");
        List<EduSubject> oneSubjects = baseMapper.selectList(wrapperOne);

        // 2. 查询出所有二级分类
        QueryWrapper<EduSubject> wrapperTwo = new QueryWrapper<>();
        wrapperTwo.ne("parent_id", "0");
        List<EduSubject> twoSubjects = baseMapper.selectList(wrapperTwo);

        // 创建 list 集合，用户存储最终封装数据
        List<OneSubject> subjectList = new ArrayList<>();

        // 3. 封装一级分类
        for (EduSubject subject : oneSubjects) {
            OneSubject oneSubject = new OneSubject();
            // oneSubject.setId(subject.getId());
            // oneSubject.setTitle(subject.getTitle());
            BeanUtils.copyProperties(subject, oneSubject);

            // 4. 封装二级分类
            List<TwoSubject> twoFinalSubject = new ArrayList<>();
            for (EduSubject tSubject : twoSubjects) {
                TwoSubject twoSubject = new TwoSubject();
                if (subject.getId().equals(tSubject.getParentId())) {
                    BeanUtils.copyProperties(tSubject, twoSubject);
                    twoFinalSubject.add(twoSubject);
                }
            }

            oneSubject.setChildren(twoFinalSubject);
            subjectList.add(oneSubject);
        }
        return subjectList;
    }
}
